import 'dart:async';

import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';

///基础界面切换Widget的Bloc
class PageBloc extends Bloc<PageEvent, PageState> {
  BuildContext context;

  @override
  PageState get initialState => PageInitState();

  @override
  Stream<PageState> mapEventToState(PageEvent event) async* {
    if (event is PageLogicEvent) {
      yield PageBuildState(pageBuilder: (BuildContext context) {
        return LogicPage(event.logicParam);
      });
    }

    if (event is PageSwitchEvent) {
      yield PageBuildState(pageBuilder: event.widgetBuilder);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  void switchPage(Widget child) {
    dispatch(
      PageSwitchEvent(
        widgetBuilder: (BuildContext context) {
          return child;
        },
      ),
    );
  }
}

//-------------------------Event事件-开始-------------------------
class PageSwitchEvent extends PageEvent {
  final WidgetBuilder widgetBuilder;

  PageSwitchEvent({@required this.widgetBuilder}) : super([widgetBuilder]);

  @override
  String toString() => 'switch';
}

class PageLogicEvent extends PageEvent {
  final LogicParam logicParam;

  PageLogicEvent({@required this.logicParam}) : super([logicParam]);

  @override
  String toString() => 'logic-${logicParam.type}';
}

//-------------------------Event事件-结束-------------------------

//-------------------------State状态-开始-------------------------

///构建界面的状态
class PageBuildState extends PageState {
  final WidgetBuilder pageBuilder;

  PageBuildState({@required this.pageBuilder}) : super([pageBuilder]);
}

///构建界面的状态
class PageInitState extends PageBuildState {
  PageInitState()
      : super(pageBuilder: (BuildContext context) {
          return LogicPage(LogicParam.loading());
        });
}

//-------------------------State状态-结束-------------------------
